package com.example.baseappstore.utils;

import android.app.NotificationChannel;
import android.app.NotificationManager;
import android.content.Context;
import android.os.Build;

import androidx.core.app.NotificationCompat;

import com.example.baseappstore.R;

import java.math.BigDecimal;
import java.math.RoundingMode;

public class NotificationHelper {

    private static final String CHANNEL_ID = "default_channel_id";
    private static final int NOTIFICATION_ID = 1;
    private final Context context;
    private NotificationManager notificationManager;
    private NotificationCompat.Builder builder;
    private int totalProgress = -1;

    public NotificationHelper(Context context) {
        this.context = context;
    }


    // 更新进度
    public void updateProgress(int progress) {
        builder.setProgress(totalProgress, progress, false).setContentText("当前进度" + BigDecimal.valueOf((float) progress * 100 / totalProgress).
                setScale(2, RoundingMode.HALF_UP) + "%");
        notificationManager.notify(NOTIFICATION_ID, builder.build());
    }


    // 创建通知渠道
    public void createNotificationChannel() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            CharSequence name = "Default Channel";
            String description = "This is the default notification channel.";
            int importance = NotificationManager.IMPORTANCE_DEFAULT;
            NotificationChannel channel = new NotificationChannel(CHANNEL_ID, name, importance);
            channel.setDescription(description);

            notificationManager = context.getSystemService(NotificationManager.class);
            if (notificationManager != null) {
                notificationManager.createNotificationChannel(channel);
            }
        }
    }

    // 发送通知
    public void sendNotification(String title, String content, int maxProgress, int currentProgress) {
        totalProgress = maxProgress;
        builder = new NotificationCompat.Builder(context, CHANNEL_ID)
                .setSmallIcon(R.mipmap.ic_launcher)
                .setContentTitle(title)
                .setContentText(content)
                .setPriority(NotificationCompat.PRIORITY_DEFAULT)
                .setProgress(maxProgress, 0, true)
                .setAutoCancel(false);  // 通知被点击后消失

        notificationManager.notify(NOTIFICATION_ID, builder.build());
    }
}